import React, { useEffect, useState, useCallback } from 'react';
import axios from '../.././service/index';
import { FloatButton } from 'antd';
import { useParams, useLocation } from 'react-router-dom';
import { ShoppingCart } from '@react-vant/icons';
import { ActionBar, Cell, Popup, Button } from 'react-vant';
import { CartO, WapHomeO, Bars, Contact } from '@react-vant/icons';
import './index.scss';

export default function Clothes() {
  const params = useParams();
  const location = useLocation();
  const [list, setList] = useState([]);
  const [num, setNum] = useState(0);
  const { keyword } = location.state || {};
  const [showCloseIcon, setShowCloseIcon] = useState(false);
  const [color] = useState(['黑色', '白色', '蓝色']);
  const [size] = useState(['S', 'M', 'L', 'XL']);
  const [carnum, setCarnum] = useState(0);
  const [carList, setCarList] = useState([]);
  const [selectedColor, setSelectedColor] = useState();
  const [selectedSize, setSelectedSize] = useState();
  const [selectedQuantity, setSelectedQuantity] = useState(0);
  const [loading, setLoading] = useState(false);
  const [loadedDataCount, setLoadedDataCount] = useState(0);
  const itemsPerPage = 4;

  const getlist = useCallback(
    async (keyword, limit, offset) => {
      const params = {
        tid: params.id,
        limit: limit,
        offset: offset,
      };

      if (keyword) {
        params.name = keyword;
      }

      try {
        const { data } = await axios.get('/clothes_list', { params });
        return data.data;
      } catch (error) {
        console.error('Error fetching data:', error);
        return [];
      }
    },
    [params.id]
  );

  const sortPrice = () => {
    const sortedList = [...list];
    if (num === 0) {
      sortedList.sort((a, b) => a.price - b.price);
      setNum(1);
    } else {
      sortedList.sort((a, b) => b.price - a.price);
      setNum(0);
    }
    setList(sortedList);
  };

  const updateNum = (status) => {
    if (status === 0) {
      setCarnum(carnum + 1);
      setSelectedQuantity(selectedQuantity + 1);
    } else {
      if (carnum > 0) {
        setCarnum(carnum - 1);
        setSelectedQuantity(selectedQuantity - 1);
      }
    }
  };

  const handleLoadMore = async () => {
    if (loading) return;

    setLoading(true);
    const data = await getlist(keyword, itemsPerPage, loadedDataCount);
    if (data.length > 0) {
      setTimeout(() => {
        setList((prevList) => [...prevList, ...data]);
        setLoadedDataCount(loadedDataCount + itemsPerPage);
        setLoading(false);
      }, 2000);
    } else {
      setLoading(false);
    }
  };

  useEffect(() => {
    async function fetchData() {
      const data = await getlist(keyword, itemsPerPage, loadedDataCount);
      setList(data);
      setLoadedDataCount(data.length);
    }
    fetchData();
  }, [getlist, keyword, itemsPerPage, loadedDataCount]);

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  const handleScroll = () => {
    if (
      window.innerHeight + document.documentElement.scrollTop >=
      document.documentElement.offsetHeight - 100
    ) {
      handleLoadMore();
    }
  };

  return (
    <div className="cbox">
      <div className="sort_price">
        <span onClick={sortPrice}>价格</span>
      </div>
      <div className="clothes">
        {list.map((item, index) => (
          <div key={index} className="con">
            <div>
              <img src={item.img} alt="" />
            </div>
            <div>{item.name}</div>
            <span style={{ color: 'red' }}>￥{item.price}</span>
            <span>
              <Cell onClick={() => setShowCloseIcon(true)}>
                <ShoppingCart className="shop" />
              </Cell>
            </span>
          </div>
        ))}
      </div>
      <div>
        <FloatButton.BackTop visibilityHeight="20" />
      </div>
      <div className="car">
        <Popup
          visible={showCloseIcon}
          closeable
          style={{ height: '40%' }}
          position="bottom"
          onClose={() => setShowCloseIcon(false)}
        >
          <div className="color">
            <h2>颜色</h2>
            {color.map((item, index) => (
              <span
                key={index}
                style={{ marginRight: '20px' }}
                onClick={() => setSelectedColor(item)}
              >
                {item}
              </span>
            ))}
          </div>
          <div className="color">
            <h2>尺寸</h2>
            {size.map((item, index) => (
              <span
                key={index}
                style={{ marginRight: '20px' }}
                onClick={() => setSelectedSize(item)}
              >
                {item}
              </span>
            ))}
          </div>
          <div className="num">
            <h2>购买数量</h2>
            <button onClick={() => updateNum(1)}>-</button>
            <span>{carnum}</span>
            <button onClick={() => updateNum(0)}>+</button>
          </div>
          <div className="cons">
            <Button
              type="primary"
              onClose={() => {
                setShowCloseIcon(false);
                setCarList([
                  ...carList,
                  {
                    color: selectedColor,
                    size: selectedSize,
                    quantity: selectedQuantity,
                  },
                ]);
              }}
              onClick={() => {
                setCarList([
                  ...carList,
                  {
                    color: selectedColor,
                    size: selectedSize,
                    quantity: selectedQuantity,
                  },
                ]);
              }}
            >
              确定
            </Button>
          </div>
        </Popup>
      </div>
      <div className="demo-action-bar">
        <ActionBar>
          <ActionBar.Icon icon={<WapHomeO />} text="首页" style={{ marginLeft: '10px' }} />
          <ActionBar.Icon icon={<Bars />} text="分类" style={{ marginLeft: '40px' }} />
          <ActionBar.Icon
            icon={<CartO />}
            badge={{ content: carList.length }}
            text="购物车"
            style={{ marginLeft: '40px' }}
          />
          <ActionBar.Icon icon={<Contact />} text="个人" style={{ marginLeft: '50px' }} />
        </ActionBar>
      </div>
    </div>
  );
}
